package top.yokey.shopai.order.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.appcompat.widget.Toolbar;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alipay.sdk.app.PayTask;
import com.jeremyliao.liveeventbus.LiveEventBus;

import top.yokey.shopai.R;
import top.yokey.shopai.order.viewmodel.OrderPayVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.arouter.ARoutePath;
import top.yokey.shopai.zcom.base.BaseActivity;
import top.yokey.shopai.zcom.help.DialogHelp;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.util.ConvertUtil;
import top.yokey.shopai.zcom.util.VerifyUtil;
import top.yokey.shopai.zsdk.ShopAISdk;
import top.yokey.shopai.zsdk.data.OrderPayData;

@Route(path = ARoutePath.ORDER_PAY)
public class OrderPayActivity extends BaseActivity {

    private final OrderPayData data = new OrderPayData();
    @SuppressLint("HandlerLeak")
    @SuppressWarnings("deprecation")
    private final Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    LiveEventBus.get(Constant.DATA_REFRESH).post(true);
                    ToastHelp.get().show(R.string.paySuccess);
                    onReturn(false);
                    break;
                case 2:
                    ToastHelp.get().show(R.string.payFailure);
                    break;
            }
        }
    };
    @Autowired(name = Constant.DATA_SN)
    String paySn;
    private Toolbar mainToolbar = null;
    private AppCompatTextView priceTextView = null;
    private AppCompatTextView snTextView = null;
    private LinearLayoutCompat preDepositLinearLayout = null;
    private AppCompatCheckBox preDepositCheckBox = null;
    private AppCompatTextView preDepositTextView = null;
    private LinearLayoutCompat rechargeCardLinearLayout = null;
    private AppCompatTextView rechargeCardTextView = null;
    private AppCompatCheckBox rechargeCardCheckBox = null;
    private LinearLayoutCompat alipayLinearLayout = null;
    private AppCompatCheckBox alipayCheckBox = null;
    private LinearLayoutCompat wechatLinearLayout = null;
    private AppCompatCheckBox wechatCheckBox = null;
    private AppCompatTextView payTextView = null;
    private WebView mainWebView = null;
    private double amount = 0.0;
    private double preDeposit = 0.0;
    private double rechargeCard = 0.0;
    private boolean memberPaypwd = false;
    private OrderPayVM vm = null;

    @Override
    public void initView() {

        setContentView(R.layout.activity_order_pay);
        mainToolbar = findViewById(R.id.mainToolbar);
        priceTextView = findViewById(R.id.priceTextView);
        snTextView = findViewById(R.id.snTextView);
        preDepositLinearLayout = findViewById(R.id.preDepositLinearLayout);
        preDepositTextView = findViewById(R.id.preDepositTextView);
        preDepositCheckBox = findViewById(R.id.preDepositCheckBox);
        rechargeCardLinearLayout = findViewById(R.id.rechargeCardLinearLayout);
        rechargeCardTextView = findViewById(R.id.rechargeCardTextView);
        rechargeCardCheckBox = findViewById(R.id.rechargeCardCheckBox);
        alipayLinearLayout = findViewById(R.id.alipayLinearLayout);
        alipayCheckBox = findViewById(R.id.alipayCheckBox);
        wechatLinearLayout = findViewById(R.id.wechatLinearLayout);
        wechatCheckBox = findViewById(R.id.wechatCheckBox);
        payTextView = findViewById(R.id.payTextView);
        mainWebView = findViewById(R.id.mainWebView);

    }

    @Override
    public void initData() {

        if (VerifyUtil.isEmpty(paySn)) {
            ToastHelp.get().showDataError();
            onReturn(false);
            return;
        }
        App.get().setWebView(mainWebView);
        setToolbar(mainToolbar, R.string.orderPay);
        observeKeyborad(R.id.mainLinearLayout);
        snTextView.setText(String.format(getString(R.string.orderPaySn), paySn));
        vm = getVM(OrderPayVM.class);
        vm.getData(paySn);

    }

    @Override
    public void initEvent() {

        preDepositLinearLayout.setOnClickListener(view -> {
            preDepositCheckBox.setChecked(true);
            rechargeCardCheckBox.setChecked(false);
            alipayCheckBox.setChecked(false);
            wechatCheckBox.setChecked(false);
        });

        rechargeCardLinearLayout.setOnClickListener(view -> {
            preDepositCheckBox.setChecked(false);
            rechargeCardCheckBox.setChecked(true);
            alipayCheckBox.setChecked(false);
            wechatCheckBox.setChecked(false);
        });

        alipayLinearLayout.setOnClickListener(view -> {
            preDepositCheckBox.setChecked(false);
            rechargeCardCheckBox.setChecked(false);
            alipayCheckBox.setChecked(true);
            wechatCheckBox.setChecked(false);
        });

        wechatLinearLayout.setOnClickListener(view -> {
            preDepositCheckBox.setChecked(false);
            rechargeCardCheckBox.setChecked(false);
            alipayCheckBox.setChecked(false);
            wechatCheckBox.setChecked(true);
        });

        payTextView.setOnClickListener(view -> pay());

        mainWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                DialogHelp.get().dismiss();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!(url.startsWith("http") || url.startsWith("https"))) {
                    return true;
                }
                PayTask task = new PayTask(OrderPayActivity.this);
                boolean success = task.payInterceptorWithUrl(url, true, result -> {
                    String returnUrl = result.getReturnUrl();
                    String resultCode = result.getResultCode();
                    if (!VerifyUtil.isEmpty(returnUrl)) {
                        OrderPayActivity.this.runOnUiThread(() -> view.loadUrl(returnUrl));
                    }
                    if (resultCode.equals("9000")) {
                        Message msg = new Message();
                        msg.what = 1;
                        mHandler.sendMessage(msg);
                    } else {
                        Message msg = new Message();
                        msg.what = 2;
                        mHandler.sendMessage(msg);
                    }
                });
                if (!success) {
                    view.loadUrl(url);
                }
                return true;
            }
        });

    }

    @Override
    public void initObserve() {

        vm.getBuyLiveData().observe(this, bean -> {
            priceTextView.setText("￥");
            priceTextView.append(bean.getPayAmount());
            snTextView.setText(String.format(getString(R.string.orderPaySn), bean.getPaySn()));
            preDepositTextView.append("（￥" + bean.getMemberAvailablePd() + "）");
            rechargeCardTextView.append("（￥" + bean.getMemberAvailableRcb() + "）");
            amount = ConvertUtil.string2Double(bean.getPayAmount());
            preDeposit = ConvertUtil.string2Double(bean.getMemberAvailablePd());
            rechargeCard = ConvertUtil.string2Double(bean.getMemberAvailableRcb());
            memberPaypwd = bean.isMemberPaypwd();
        });

        vm.getPayPasswordLiveData().observe(this, string -> vm.payNew(data));

        vm.getPayLiveData().observe(this, string -> {
            LiveEventBus.get(Constant.DATA_REFRESH).post(true);
            ToastHelp.get().show(R.string.paySuccess);
        });

        vm.getErrorLiveData().observe(this, bean -> {
            switch (bean.getCode()) {
                case 1:
                    DialogHelp.get().query(get(), R.string.loadFailure, bean.getReason(), view -> onReturn(false), view -> vm.getData(paySn));
                    break;
                case 2:
                    ToastHelp.get().show(bean.getReason());
                    showInputPayPwd();
                    break;
                case 3:
                    LiveEventBus.get(Constant.DATA_REFRESH).post(true);
                    ToastHelp.get().show(R.string.paySuccess);
                    onReturn(false);
                    break;
            }
        });

    }

    //自定义方法

    private void pay() {

        data.setPdPay("0");
        data.setRcbPay("0");
        data.setPaySn(paySn);
        data.setPassword("");
        data.setPaymentCode("alipay");

        //预存款支付
        if (preDepositCheckBox.isChecked()) {
            if (preDeposit <= 0 && preDeposit < amount) {
                ToastHelp.get().show(R.string.tipsPreDepositNoHave);
                return;
            }
            if (!memberPaypwd) {
                tipsPayPwd();
                return;
            }
            data.setPdPay("1");
            showInputPayPwd();
            return;
        }

        //充值卡支付
        if (rechargeCardCheckBox.isChecked()) {
            if (rechargeCard <= 0 && rechargeCard < amount) {
                ToastHelp.get().show(R.string.tipsRechargeCardNoHave);
                return;
            }
            if (!memberPaypwd) {
                tipsPayPwd();
                return;
            }
            data.setRcbPay("1");
            showInputPayPwd();
            return;
        }

        //支付宝支付
        if (alipayCheckBox.isChecked()) {
            DialogHelp.get().progress(get(), R.string.handlerIng);
            mainWebView.loadUrl(ShopAISdk.get().getOrderAlipayUrl(paySn));
            return;
        }

        ToastHelp.get().show(R.string.pleaseChoosePayment);

    }

    private void tipsPayPwd() {

        DialogHelp.get().query(get(), R.string.loadFailure, R.string.tipsAddPayPassword, null, view -> {
            if (App.get().getMemberBean().getMemberInfoAll().getMemberMobileBind().equals("1")) {
                App.get().start(ARoutePath.MEMBER_PAY_PASSWORD);
                return;
            }
            App.get().start(ARoutePath.MEMBER_MOBILE_BIND);
        });

    }

    private void showInputPayPwd() {

        DialogHelp.get().input(
                get(),
                InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD,
                R.string.pleaseInputPayPassword,
                "",
                null,
                content -> {
                    data.setPassword(content);
                    vm.checkPdPwd(content);
                }
        );

    }

}
